﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Web;
using Lapkin.Models.DataModels;
using Ninject;

namespace Lapkin.Models.Repositories
{
    public class SqlRepository
    {
        public MainContext Db  = new MainContext();

        private readonly ProductRepository _productRepository = null;
        public ProductRepository ProductRepository {
            get { return _productRepository ?? new ProductRepository(Db, this); }
        }

        private readonly AccountRepository _accountRepository = null;
        public AccountRepository AccountRepository {
            get { return _accountRepository ?? new AccountRepository(Db, this); }
        }

        private readonly CategoryRepository _categoryRepository = null;
        public CategoryRepository CategoryRepository
        {
            get { return _categoryRepository ?? new CategoryRepository(Db, this); }
        }


        public void CheckChange<T>(T entity) where T : class
        {

            foreach (var propertyInfo in entity.GetType()
                               .GetProperties(
                                       BindingFlags.Public
                                       | BindingFlags.Instance))
            {
                object val = propertyInfo.GetValue(entity);
                if (val == null) continue;
                if (propertyInfo.PropertyType.IsGenericType) continue;
                //if (propertyInfo.PropertyType.IsClass) continue;
                if ((val is Guid) && ((Guid) val) == Guid.Empty) continue;
                if ((val is DateTime) && ((DateTime) val) == DateTime.MinValue) continue;
                if (propertyInfo.Name != "Id")
                {
                    Db.Entry(entity).Property(propertyInfo.Name).IsModified = true;
                }
            }
        }
    }
}